#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget),
      userSqlite(MonitoringUserSqlite::getInstance())
{
    ui->setupUi(this);
    m_tcpServer = new QTcpServer(this);

    if (m_tcpServer->listen(QHostAddress::Any, 6666)) {
        qDebug() << "Server started and listening on port 6666";
    } else {
        qDebug() << "Failed to start the server:" << m_tcpServer->errorString();
    }

    connect(m_tcpServer, &QTcpServer::newConnection, this, &Widget::handleNewConnection);
    connect(ui->pushButton, &QPushButton::clicked, this, [=]() {
        QByteArray data = ui->textEdit->toPlainText().toUtf8();
        sendMessageToAllClients(data);
        ui->textEdit->clear();
    });
    connect(ui->pushButton_2, &QPushButton::clicked, this, [=]() {
        for (QTcpSocket *client : m_clients) {
            client->disconnectFromHost();
            client->deleteLater();
        }
        m_clients.clear();
    });
    connect(ui->pushButton_3, &QPushButton::clicked, this, [=]() {
        ui->textBrowser->clear();
    });
}
void Widget::handleNewConnection()
{

    QTcpSocket *socket = m_tcpServer->nextPendingConnection();
    m_clients.append(socket);

    QString ipAddr = socket->peerAddress().toString();
    quint16 port = socket->peerPort();
    QString str = QString("[%1:%2]: 连接成功").arg(ipAddr).arg(port);
    ui->textBrowser->append(str);

    connect(socket, &QTcpSocket::readyRead, this, &Widget::handleClientReadyRead);
    connect(socket, &QTcpSocket::disconnected, this, &Widget::handleClientDisconnected);
}

void Widget::handleClientReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        QByteArray data = socket->readAll();
        ui->textBrowser->append(data);
        qDebug()<<"handleClientReadyRead";
        //sendMessageToAllClients(data);
        handleSingleClientMessage(data, socket);
    }
}
void Widget::handleClientDisconnected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (socket) {
        QString ipAddr = socket->peerAddress().toString();
        quint16 port = socket->peerPort();
        QString str = QString("[%1:%2]: 断开连接").arg(ipAddr).arg(port);
        ui->textBrowser->append(str);

        m_clients.removeOne(socket);
        socket->deleteLater();
    }
}

void Widget::sendMessageToAllClients(const QByteArray &data)
{

    for (QTcpSocket *client : m_clients) {
        if (client->state() == QTcpSocket::ConnectedState) {
            handleSingleClientMessage(data, client);
        }
    }
}
void Widget::handleSingleClientMessage(const QByteArray &data, QTcpSocket *client)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    QJsonObject jsonObj = jsonDoc.object();
    QString action = jsonObj["action"].toString();
    qDebug() << "处理消息，action:" << action;
    if (action == "regist") {
        sendRegist(jsonObj, client);
    } else if (action == "login") {
        sendLogin(jsonObj, client);
    } else if (action == "forgot") {
        sendForgot(jsonObj, client);
    } else if (action == "main") {
        sendMain(jsonObj, client);
    }else if (action == "ChangeEmail") {
        sendChangeEmail(jsonObj, client);
    }else if (action=="changepass") {
        sendChangePass(jsonObj, client);
    }else if(action == "addDevice"){
        sendAddDevice(jsonObj, client);
    }else if(action == "deviceList"){
        sendDeviceList(jsonObj, client);
    }else if (action == "deviceDelete") {
        sendDeviceDelete(jsonObj, client);
    }else if (action == "deviceUpdate") {
        sendDeviceUpdate(jsonObj);
    }else if (action == "realdata") {
        sendDataRealData(jsonObj);
    }else if (action == "selectAllData") {
        sendSelectAllData(jsonObj, client);
    }else if (action == "selectReasonData") {
        sendSelectReasonData(jsonObj, client);
    }else if (action == "warnrole") {
        sendWarnRoleData(jsonObj, client);
    }else if (action == "getwarnrole") {
        sendGetWarnRoleData(jsonObj, client);
    }else if (action == "warnrecode") {
        sendWarnRecodeData(jsonObj);
    }else if (action == "getwarnrecode") {
        sendGetWarnRecodeData(jsonObj, client);
    }else if (action == "deviceGroupList") {
        sendDeviceGroupList(jsonObj, client);
    }
}



Widget::~Widget()
{
    delete ui;
}

void Widget::sendRegist(const QJsonObject& jsonObj,QTcpSocket *client)
{
    //注册
    QString username = jsonObj["username"].toString();
    QString password = jsonObj["password"].toString();
    QString role = jsonObj["role"].toString();
    QString email = jsonObj["email"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="regist";
    jsonObjResult["code"]="2";
    if(userSqlite.insertData(username,password,email,role)==QUERY_SUCCESS_USER_EXISTS){
        jsonObjResult["code"]="0";
    }
    if(userSqlite.insertData(username,password,email,role)==QUERY_FAILED){
        jsonObjResult["code"]="3";
    }

    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendLogin(const QJsonObject &jsonObj, QTcpSocket *client)
{
    //登录
    QString username = jsonObj["username"].toString();
    QString password = jsonObj["password"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="login";
    jsonObjResult["code"]="2";
    if(userSqlite.loginGetData(username,password)==QUERY_SUCCESS_USER_NOT_EXISTS){
        jsonObjResult["code"]="1";
    }
    if(userSqlite.loginGetData(username,password)==QUERY_FAILED){
        jsonObjResult["code"]="3";
    }


    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendForgot(const QJsonObject &jsonObj, QTcpSocket *client)
{
    qDebug()<<"忘记密码";
    //忘记密码
    QString username = jsonObj["username"].toString();
    QString password = jsonObj["password"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="forgot";
    jsonObjResult["code"]="2";
    if(userSqlite.changePassword(username,password)==QUERY_SUCCESS_USER_NOT_EXISTS){
        jsonObjResult["code"]="1";
    }
    if(userSqlite.changePassword(username,password)==QUERY_FAILED){
        jsonObjResult["code"]="3";
    }


    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendMain(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString username = jsonObj["username"].toString();
    userModel*model=userSqlite.getSqLite(username);
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="main";
    jsonObjResult["id"]=model->id;
    jsonObjResult["username"]=model->username;
    jsonObjResult["password"]=model->password;
    jsonObjResult["role"]=model->role;
    jsonObjResult["email"]=model->emial;
    jsonObjResult["created_at"]=model->created_at;
    jsonObjResult["updated_at"]=model->updated_at;
    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();

}

void Widget::sendChangeEmail(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString username = jsonObj["username"].toString();
    QString emial = jsonObj["email"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="ChangeEmail";
    jsonObjResult["code"]="2";
    if(userSqlite.changeEmail(username,emial)==QUERY_SUCCESS){
        jsonObjResult["code"]="2";
    }else{
        jsonObjResult["code"]="0";
    }
    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendChangePass(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString username = jsonObj["username"].toString();
    QString password = jsonObj["password"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="changepass";
    jsonObjResult["code"]="2";
    if(userSqlite.changePassword(username,password)==QUERY_SUCCESS){
        jsonObjResult["code"]="2";
    }else{
        jsonObjResult["code"]="0";
    }

    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendAddDevice(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString user_id = jsonObj["user_id"].toString();
    QString name = jsonObj["name"].toString();
    QString type = jsonObj["type"].toString();
    QString location = jsonObj["location"].toString();
    QString manufacturer = jsonObj["manufacturer"].toString();
    QString model = jsonObj["model"].toString();
    QString status = jsonObj["status"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="addDevice";
    jsonObjResult["code"]="2";
    if(userSqlite.insertDeviceData(user_id,name,type,location,manufacturer,model,status)==QUERY_SUCCESS){

        jsonObjResult["code"]="2";
    }else {
        jsonObjResult["code"]="0";
    }
    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();

}

void Widget::sendDeviceList(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString user_id = jsonObj["user_id"].toString();
    QJsonObject rootObject;
    rootObject["action"] = "deviceList";
    QJsonArray jsonArray;
    QList<deviceModel> list=userSqlite.checkList();
    for (const auto&device:list) {
        QJsonObject jsonObject;
        jsonObject["id"] = device.id;
        jsonObject["user_id"] = device.user_id;
        jsonObject["name"] = device.name;
        jsonObject["type"] = device.type;
        jsonObject["location"] = device.location;
        jsonObject["manufacturer"] = device.manufacturer;
        jsonObject["model"] = device.model;
        jsonObject["status"] = device.status;
        jsonObject["installation_date"] = device.installation_date;
        jsonArray.append(jsonObject);
    }
    rootObject["data"] = jsonArray;
    QJsonDocument jsonDocresult(rootObject);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendDeviceDelete(const QJsonObject &jsonObj,QTcpSocket *client)
{
    QString user_id = jsonObj["id"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="deviceDelete";
    jsonObjResult["code"]="2";
    if(userSqlite.deviceDelete(user_id)==QUERY_SUCCESS){

        jsonObjResult["code"]="2";
    }else {
        jsonObjResult["code"]="0";
    }
    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendDeviceUpdate(const QJsonObject &jsonObj)
{
    //deviceUpdate
    QString user_id = jsonObj["user_id"].toString();
    QString id = jsonObj["id"].toString();
    QString str = jsonObj["str"].toString();
    QString col = jsonObj["col"].toString();
    userSqlite.deviceUpdate(str,id,user_id,col);

}

void Widget::sendDataRealData(const QJsonObject &jsonObj)
{
    QString user_id = jsonObj["user_id"].toString();
    QString device_id = jsonObj["device_id"].toString();
    QString temperature = jsonObj["temperature"].toString();
    QString humidity = jsonObj["humidity"].toString();
    QString light = jsonObj["light"].toString();
    QString co2 = jsonObj["co2"].toString();
    QString pressure = jsonObj["pressure"].toString();
    userSqlite.insertDataData(user_id,device_id,temperature,humidity,light,co2,pressure);
}

void Widget::sendSelectAllData(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString device_id = jsonObj["user_id"].toString();
    QJsonObject rootObject;
    rootObject["action"] = "selectAllData";
    QJsonArray jsonArray;
    QList<dataModel> list=userSqlite.selectAllDataData();
    for (const auto&data:list) {
        QJsonObject jsonObject;
        jsonObject["id"] = data.id;
        jsonObject["user_id"] = data.user_id;
        jsonObject["device_id"] = data.device_id;
        jsonObject["timestamp"] = data.timestamp;
        jsonObject["temperature"] = data.temperature;
        jsonObject["humidity"] = data.humidity;
        jsonObject["light"] = data.light;
        jsonObject["co2"] = data.co2;
        jsonObject["pressure"] = data.pressure;
        jsonArray.append(jsonObject);
    }
    rootObject["data"] = jsonArray;
    QJsonDocument jsonDocresult(rootObject);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendSelectReasonData(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString device_id = jsonObj["device_id"].toString();
    QString user_id = jsonObj["user_id"].toString();
    QString startTime = jsonObj["startTime"].toString();
    QString endTime = jsonObj["endTime"].toString();
    QJsonObject rootObject;
    rootObject["action"] = "selectReasonData";
    QJsonArray jsonArray;
    QList<dataModel> list=userSqlite.selectDataToReasonData(startTime,endTime,device_id);
    for (const auto&data:list) {
        QJsonObject jsonObject;
        jsonObject["id"] = data.id;
        jsonObject["user_id"] = data.user_id;
        jsonObject["device_id"] = data.device_id;
        jsonObject["timestamp"] = data.timestamp;
        jsonObject["temperature"] = data.temperature;
        jsonObject["humidity"] = data.humidity;
        jsonObject["light"] = data.light;
        jsonObject["co2"] = data.co2;
        jsonObject["pressure"] = data.pressure;
        jsonArray.append(jsonObject);
    }
    rootObject["data"] = jsonArray;
    QJsonDocument jsonDocresult(rootObject);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendWarnRoleData(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString device_id = jsonObj["device_id"].toString();
    QString description = jsonObj["description"].toString();
    QString maxHemperature = jsonObj["maxHemperature"].toString();
    QString minHemperature = jsonObj["minHemperature"].toString();
    QString maxTemperature = jsonObj["maxTemperature"].toString();
    QString minTemperature = jsonObj["minTemperature"].toString();
    QString action = jsonObj["actiond"].toString();
    QJsonObject jsonObjResult;
    jsonObjResult["action"] ="warnrole";
    jsonObjResult["code"]="2";
    if(userSqlite.insertWarnRoleData(device_id,description,maxHemperature,minHemperature,maxTemperature,minTemperature,action)==QUERY_SUCCESS){

        jsonObjResult["code"]="2";
    }else {
        jsonObjResult["code"]="0";
    }
    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendGetWarnRoleData(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString device_id = jsonObj["device_id"].toString();

    warnRoleModel*model=userSqlite.getWarnRoleSqLite(device_id);

    QJsonObject jsonObjResult;
    if(model==nullptr){
        jsonObjResult["action"] ="getwarnrole";
        jsonObjResult["id"]="-1";
    }else {
        jsonObjResult["action"] ="getwarnrole";
        jsonObjResult["id"]=model->id;
        jsonObjResult["device_id"]=model->device_id;
        jsonObjResult["description"]=model->description;
        jsonObjResult["maxHemperature"]=model->maxHemperature;
        jsonObjResult["minHemperature"]=model->minHemperature;
        jsonObjResult["maxTemperature"]=model->maxTemperature;
        jsonObjResult["minTemperature"]=model->minTemperature;
        jsonObjResult["actiond"]=model->action;
    }

    QJsonDocument jsonDocresult(jsonObjResult);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);
    qDebug()<<"device_id=="<<jsonDataBytesresult;
    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendWarnRecodeData(const QJsonObject &jsonObj)
{

    QString device_id = jsonObj["device_id"].toString();
    QString content = jsonObj["content"].toString();
    QString status = jsonObj["status"].toString();
    QString note = jsonObj["note"].toString();
    userSqlite.insertWarnRecodeData(device_id,content,status,note);

}

void Widget::sendGetWarnRecodeData(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QJsonObject rootObject;
    rootObject["action"] = "getwarnrecode";
    QJsonArray jsonArray;
    QList<warnRecode> list=userSqlite.getWarnRecodeData();
    for (const auto&data:list) {
        QJsonObject jsonObject;
        jsonObject["id"] = data.id;
        jsonObject["device_id"] = data.device_id;
        jsonObject["timestamp"] = data.timestamp;
        jsonObject["content"] = data.content;
        jsonObject["status"] = data.status;
        jsonObject["note"] = data.note;
        jsonArray.append(jsonObject);
    }
    rootObject["data"] = jsonArray;
    QJsonDocument jsonDocresult(rootObject);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

void Widget::sendDeviceGroupList(const QJsonObject &jsonObj, QTcpSocket *client)
{
    QString type = jsonObj["type"].toString();
    qDebug()<<"type==="<<type;
    QJsonObject rootObject;
    rootObject["action"] = "deviceGroupList";
    QJsonArray jsonArray;
    QList<deviceModel> list=userSqlite.getDeviceGroupListSqLite(type);
    //qDebug()<<"sendDeviceGroupList"<<list;
    for (const auto&data:list) {
        QJsonObject jsonObject;
        jsonObject["id"] = data.id;
        jsonObject["user_id"] = data.user_id;
        jsonObject["name"] = data.name;
        jsonObject["type"] = data.type;
        jsonObject["location"] = data.location;
         jsonObject["manufacturer"] = data.manufacturer;
        jsonObject["model"] = data.model;
        jsonObject["status"] = data.status;
        jsonObject["installation_date"] = data.installation_date;
        jsonArray.append(jsonObject);
    }
    rootObject["data"] = jsonArray;
    QJsonDocument jsonDocresult(rootObject);
    QByteArray jsonDataBytesresult = jsonDocresult.toJson(QJsonDocument::Compact);

    client->write(jsonDataBytesresult);
    client->flush();
}

